package i2.application.fmw.aspects;

import i2.application.fmw.exceptions.ValidationException;
import i2.application.fmw.exceptions.ValidationMessage;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Aspect
public class ValidationAspect {

	private static final Logger logger = LoggerFactory.getLogger(ValidationAspect.class);


//	@Before("execution(* i2.application.checklist.services.impl..* (..))")
	@Before("@annotation(i2.application.fmw.aspects.Validation)")
	public void validate(JoinPoint jp)  {

		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		Validator validator = factory.getValidator();

		logger.debug("appel de validate sur la méthode : {} avec {}",jp.getSignature().getName(), jp.getArgs()[0].toString());
		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(jp.getArgs()[0]); // TODO BEWARE !!!! un seul objet en paramètre !!!!!!! pour la validation

		logger.debug("Nombre de contraintes automatiques violées : {}", constraintViolations.size());
		
		ValidationException validationException = new ValidationException();
		
		if (!constraintViolations.isEmpty()) {
			for (ConstraintViolation<?> cons : constraintViolations) {
				logger.warn(cons.getMessage());
				validationException.add(new ValidationMessage(cons));
			}

			throw validationException;
		}

	}
}

